<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>任务表单</title>
    <!-- 依 赖 样 式 -->
    <link rel="stylesheet" href="../module/pear/css/pear.css"/>
</head>
<body class="pear-container">
<form class="layui-form" id="task">
    <div class="layui-form-item">
        <label class="layui-form-label">任务名称</label>
        <div class="layui-input-block">
            <input type="text" name="name" placeholder="请输入任务名称" autocomplete="off"
                   class="layui-input"/>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">网址</label>
        <div class="layui-input-block">
            <input type="text" name="url" placeholder="请输入启动网址" autocomplete="off"
                   class="layui-input"/>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label">输出类型</label>
        <div class="layui-input-block">
            <select name="taskType">
                <option value="ONLY_OPERATE">不输出</option>
                <option value="JSON">JSON</option>
                <option value="INSERT_SQL" disabled="">INSERT SQL</option>
            </select>
        </div>
    </div>
</form>
<div class="layui-card-body">
    <input type="button" class="pear-btn pear-btn-success" id="addStep" value="添加步骤"/>
    <input type="button" class="pear-btn pear-btn-success" id="save" value="保存"/>
</div>
<table class="layui-table" lay-skin="line">
    <colgroup>
        <col width="100">
        <col width="80">
        <col width="100">
        <col width="150">
        <col width="100">
        <col width="80">
    </colgroup>
    <thead>
    <tr>
        <th>操作</th>
        <th>标识类型</th>
        <th>标识值</th>
        <th>其他值</th>
        <th>字段名</th>
        <th></th>
    </tr>
    </thead>
    <tbody id="steps">
    </tbody>
</table>
<p style="margin-left: 45%" hidden id="null">暂无步骤</p>
</body>
<!-- 依 赖 脚 本 -->
<script src="../module/layui/layui.js"></script>
<script src="../module/pear/pear.js"></script>
<script>
    let AllSteps = []
    layui.use(['layer', 'jquery', 'form', 'tool', 'request'], function () {
        let $ = layui.jquery
        let tool = layui.tool
        let request = layui.request
        let form = layui.form
        let index = tool.getRequestVal("index")
        let copy = tool.getRequestVal("copy")
        console.log("copy:" + copy)
        if (index !== false) {
            parent.window.contentWin.cacheTab['task' + index] = window
            alert(JSON.stringify({
                type: 'function',
                method: 'getTask',
                index: index
            }))
            if (copy === '1')
                index = false
        }

        $('#addStep').click(() => {
            openStep()
        })

        $('#save').click(() => {
                if (parent.window.contentWin.state) {
                    layui.tool.toast.warning('提示', '正在执行任务，请停止后再操作');
                    return false
                }
                let data = tool.serializeObject($('#task'))
                if (tool.isBlank(data.name)) {
                    tool.toast.warning('表单验证错误', '请填写任务名称', 'topCenter')
                    return false
                }
                if (tool.isBlank(data.url)) {
                    tool.toast.warning('表单验证错误', '请填写任务网址', 'topCenter')
                    return false
                } else if (data.url.indexOf('http://') !== 0 && data.url.indexOf('https://') !== 0) {
                    tool.toast.warning('表单验证错误', '任务网址不正确！ http:// || https://', 'topCenter')
                    return false
                }
                if (AllSteps.length === 0) {
                    tool.toast.warning('任务验证错误', '请添加任务步骤', 'topCenter')
                    return false
                }
                data['steps'] = AllSteps
                parent.window.layui.tool.loading.Load(3, "请稍后..");
                if (index !== false) {
                    alert(JSON.stringify({
                        type: 'function',
                        method: 'editTask',
                        data: JSON.stringify({index: index, data: data})
                    }))
                } else {
                    alert(JSON.stringify({
                        type: 'function',
                        method: 'saveTask',
                        data: JSON.stringify(data)
                    }))
                }
            }
        )
    })

    function refListView() {
        let $ = layui.jquery
        let tool = layui.tool
        $('#steps').html('')
        let steps = ''
        $.each(AllSteps, function (i, t) {
            // console.log(JSON.stringify(t))
            let b = ''
            let bv = ''
            if (tool.isNotBlank(t.id)) {
                b = 'ID'
                bv = t.id
            } else if (tool.isNotBlank(t.className)) {
                b = 'Class [' + (t.index == null ? "" : t.index) + ']'
                bv = t.className
            } else if (tool.isNotBlank(t.name)) {
                b = 'Name [' + (t.index == null ? "" : t.index) + ']'
                bv = t.name
            } else if (tool.isNotBlank(t.tag)) {
                b = 'Tag [' + (t.index == null ? "" : t.index) + ']'
                bv = t.tag
            } else if (tool.isNotBlank(t.xpath)) {
                b = 'Xpath'
                bv = t.xpath
            }
            let topR = "<input type=\"button\" class=\"pear-btn pear-btn-primary pear-btn-xs \"  onclick='topR(" + i + ")' value=\"上移\"/>"
            let downR = "<input type=\"button\" class=\"pear-btn pear-btn-primary pear-btn-xs \"  onclick='downR(" + i + ")' value=\"下移\"/>"

            steps += "<tr>" +
                "<td>" + typeMap[t.type] + "</td>" +
                "<td>" + b + "</td>" +
                "<td>" + bv + "</td>" +
                "<td>" + t.value + "</td>" +
                "<td>" + t.fieName + "</td>" +
                "<td>";
            if (i === 0) {
                steps += downR
            } else if (i === AllSteps.length - 1) {
                steps += topR
            } else {
                steps += topR + downR
            }
            steps += "<input type=\"button\" class=\"pear-btn pear-btn-warming pear-btn-xs \"  onclick='edit(" + i + ")' value=\"编辑\"/>" +
                "<input type=\"button\" class=\"pear-btn pear-btn-danger pear-btn-xs \" onclick='del(" + i + ")' value=\"删除\"/>" +
                "</td>" +
                "</tr>";
        })
        $('#steps').html(steps)
        if (AllSteps.length === 0) {
            $('#null').show()
        } else
            $('#null').hide()
    }

    function topR(i) {
        let top = AllSteps[i - 1]
        AllSteps[i - 1] = AllSteps[i]
        AllSteps[i] = top
        refListView()
    }

    function downR(i) {
        let down = AllSteps[i + 1]
        AllSteps[i + 1] = AllSteps[i]
        AllSteps[i] = down
        refListView()
    }

    function del(i) {
        AllSteps.splice(i, 1)
        refListView()
    }

    function edit(i) {
        openStep(AllSteps[i], i)
    }

    function openStep(d, i) {
        layer.open({
            type: 2,
            title: '添加步骤',
            shade: 0.1,
            area: ['80%', '80%'],
            btn: ['确定'],
            content: parent.window.jsConnector.HTML_PATH + '/step.html',
            yes: function (index, layero) {
                const iframeWin = window[layero.find('iframe')[0]['name']];
                const formData = iframeWin.saveStep();
                if (formData !== false) {
                    if (iframeWin.getIndex() !== -1)
                        AllSteps[iframeWin.getIndex()] = formData
                    else
                        AllSteps.push(formData)
                    layer.close(index);
                }
            },
            success: function (layero, index) {
                var iframeWin = window[layero.find('iframe')[0]['name']];
                iframeWin.init(d, i);
            },
            end: function (layero, index) {
                refListView();
            }
        });
    }


    function showData(data) {
        layui.tool.JsonToHtmlValByName(data, layui.jquery('#task'))
        AllSteps = data['steps']
        refListView()
        layui.form.render();
    }

    let typeMap = {
        'ELEMENT': '选择元素',
        'CLEAN_ELEMENT': '清除已选择元素',
        'CLICK': '点击',
        'INPUT': '输入',
        'OUTPUT': '输出',
        'SAVE_PHOTO': '保存图片',
        'TO': '转到',
        'REFRESH': '刷新页面',
        'JAVASCRIPT': '执行JS',
        'SUBMIT': 'form表单提交',
        'WAIT': '设置钩子',
        'SLEEP': '休息',
    }

</script>
</html>